/*
 * Filename:    IntrgityBlackController.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014年10月30日
 */
package com.paic.mhis.hcpms.trust.web.controller;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.quota.settlement.biz.service.KpiRegionCodeService;
import com.paic.mhis.hcpms.trust.biz.service.IntegrityBusinessService;
import com.paic.mhis.hcpms.trust.common.ConstantsUtils;
import com.paic.mhis.hcpms.trust.common.TrustConstants;
import com.paic.mhis.hcpms.trust.dto.BlackParamterCondtion;
import com.paic.mhis.hcpms.trust.dto.BlackPatientBaseInfoDTO;
import com.paic.mhis.hcpms.trust.dto.IntegrityBlackDTO;
import com.paic.mhis.hcpms.trust.web.vo.HhAlertMessage;
import com.paic.mhis.hcpms.trust.web.vo.IntegrityResponseBean;
import com.paic.mhis.hcpms.trust.web.vo.InterityBlackAddRequestVO;
import com.paic.pafa.appclient.annotation.BizServicesProxy;
import com.paic.pafa.exceptions.BusinessException;

@Controller
@RequestMapping("/integrityBlack/")
public class IntrgityBlackController {
	public static Log log = LogFactory.getLog(IntrgityBlackController.class);

	@BizServicesProxy(beanName = "integrityBusinessServiceImpl")
	private IntegrityBusinessService service;

	@BizServicesProxy(beanName = "kpiRegionCodeService")
	private KpiRegionCodeService kpiRegionCodeService;

	public static final String fileNamePath = "views/hcpms/achievements/integrity/参保人诚信管理导入Excel模板.xls";
	public static final String fileName = "参保人诚信管理导入Excel模板.xls";

	private String filePath;

	@Value("${reportTemplatePath}")
	private String reportTemplatePath;

	@RequestMapping("loadBlackExcelFile.do")
	@ResponseBody
	public void loadBlackExcelFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String path = filePath + fileName;

		log.info("current path==" + path);

		BufferedOutputStream bos = null;
		String disposition = "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8");
		response.setHeader("Content-disposition", disposition);
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(path);
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[2048];
			while (fis.read(buffer) != -1) {
				bos.write(buffer);
				bos.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (bos != null) {
				bos.close();
			}
		}

	}

	/**
	 * 加载所有的参保黑名单信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("checkPatientBasicExist.do")
	@ResponseBody
	public IntegrityResponseBean loadAllBlackPerson(HttpServletRequest request) {

		IntegrityResponseBean responseBean = new IntegrityResponseBean();
		String personCard = request.getParameter("personCard");
		boolean flag = this.service.processCheckBlackExist(personCard);
		responseBean.setStatus(flag);
		return responseBean;
	}

	/**
	 * 加载所有的参保黑名单信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("loadAllBlackPerson.do")
	@ResponseBody
	public IntegrityResponseBean loadAllBlackPerson(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		IntegrityResponseBean bean = new IntegrityResponseBean();

		BlackParamterCondtion parameter = new BlackParamterCondtion();
		String name = vo.getName();
		String cardNo = vo.getCardNo(); // /身份证号
		String personNo = vo.getPersonCard(); // 社保号
		String personType = vo.getPersonType(); // 人员类别

		int page = vo.getPage();
		int pageSize = vo.getPageSize();

		int start = (page - 1) * pageSize;
		int end = start + pageSize;

		parameter.setStart(start);
		parameter.setEnd(end);

		if (StringUtils.hasText(name)) {
			parameter.setName("%" + name + "%");
		}
		if (StringUtils.hasText(personNo)) {
			parameter.setPersonCard("%" + personNo + "%");
		}
		if (StringUtils.hasText(personType)) {
			parameter.setPersonType(personType);
		}
		if (StringUtils.hasText(cardNo)) {
			parameter.setCardNo("%" + cardNo + "%");
		}

		List<BlackPatientBaseInfoDTO> list = this.service.queryBlackPatientBaseInfoDTO(parameter);
		long count = this.service.queryBlackPaientBaseInfoCount(parameter);

		bean.setStatus(true);
		bean.setPatientList(list);
		bean.setTotal(count);

		return bean;
	}

	/**
	 * 根据社保号加载社保人员信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("loadPatientBasicInfo.do")
	@ResponseBody
	public IntegrityResponseBean loadPatientBasicInfo(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		String personCard = vo.getPersonCard(); // 社保号
		IntegrityResponseBean returnBean = new IntegrityResponseBean();

		if (StringUtils.hasText(personCard)) {

			IntegrityBlackDTO bean = this.service.getIntegrityBlackDTOBySociationNum(personCard);
			if (bean != null) {
				List<IntegrityBlackDTO> list = new ArrayList<IntegrityBlackDTO>();
				list.add(bean);

				returnBean.setStatus(true);
				returnBean.setResult(list);
			} else {
				returnBean.setStatus(false);
			}

		} else {
			returnBean.setStatus(false);
		}
		return returnBean;
	}

	/**
	 * 上传参保人信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("uploadIntegrityBlackExcel.do")
	@ResponseBody
	public Map<String, Object> uploadIntegrityBlackExcel(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");
		String username = user.getUsername();
		String regionCode = this.kpiRegionCodeService.getRegionCode(user.getUserId());

		IntegrityResponseBean returnBean = new IntegrityResponseBean();
		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		MultipartHttpServletRequest multiRequest = resolver.resolveMultipart(request);

		List<MultipartFile> files = multiRequest.getFiles("file");
		List<IntegrityBlackDTO> list = new ArrayList<IntegrityBlackDTO>();
		// 临时放需要匹配的临时数据 Name+CardNo+CardType 作为key值
		Map<String, Object> ibInfoMsg = new HashMap<String, Object>();

		Map<String, Object> sameInfoKeyName = null;

		if (files != null && files.size() > 0) {

			for (MultipartFile file : files) {
				try {
					InputStream is = file.getInputStream();
					HSSFWorkbook wb = new HSSFWorkbook(is);
					int sheetNum = wb.getNumberOfSheets(); // 获取sheet
					for (int i = 0; i < sheetNum; i++) {
						if (i > 0) {
							// 目前模板中仅仅 sheet[0] 才有用啦存值
							break;
						}
						HSSFSheet childSheet = wb.getSheetAt(i);
						int rowNum = childSheet.getLastRowNum();
						//验证表头
						{
							HSSFRow row0 = childSheet.getRow(0);
							boolean a=(row0.getCell(0)==null || !"姓名".equals(row0.getCell(0).getStringCellValue()));
							boolean b=(row0.getCell(1)==null || !"性别".equals(row0.getCell(1).getStringCellValue()));
							boolean c=(row0.getCell(7)==null || !"案发时间".equals(row0.getCell(7).getStringCellValue()));
							if(a||b||c){
								HashMap<String, Object> errorTemplate=new HashMap<String,Object>();
								errorTemplate.put("errorTemplate", "模板选择错误");
								return errorTemplate;
							}
						}
						// j=1 跳过head部分
						for (int j = 1; j <= rowNum; j++) {
							HSSFRow row = childSheet.getRow(j);
							if (row == null) {
								continue;
							}
							IntegrityBlackDTO currentBean = this.getIntegrityBlackDTOFromRow(row, username);
							currentBean.setRegionCode(regionCode);
							currentBean.setfJFileName(file.getOriginalFilename());
							currentBean.setfJRowNum(j);
							list.add(currentBean);
							if (currentBean.getName() == null && currentBean.getCardType() == null
									&& currentBean.getCardNo() == null) {
								continue;
								// 不再往下操作了
							}
							// start 验证重复数据-------------
							String toCpStr = currentBean.getName().trim() + currentBean.getCardType().trim()
									+ currentBean.getCardNo().trim();

							// 校验excel 重复数据
							if (ibInfoMsg.get(toCpStr) != null) {
								if (sameInfoKeyName == null) {
									sameInfoKeyName = new HashMap<String, Object>();
								}
								sameInfoKeyName.put(toCpStr, ibInfoMsg.get(toCpStr) + " ，" + j);
							} else {
								ibInfoMsg.put(toCpStr, j);
							}
							// end 验证重复数据-----------
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					Map<String,Object> map =new HashMap<String,Object>();
					map.put("errorTemplate","模板选择错误。");
					return map;
					//returnBean.setStatus(false);
					//returnBean.setMessage("上传失败" + e.getMessage());
					//log.info("**************black upload error********" + e.getMessage());
				}
			}
		}

		Map<String, Object> hhamap = new HashMap<String, Object>();
		List<HhAlertMessage> hhalist = new ArrayList<HhAlertMessage>();

		if (sameInfoKeyName != null) {
			Iterator<Entry<String, Object>> entries = sameInfoKeyName.entrySet().iterator();
			HhAlertMessage hhvo = new HhAlertMessage();
			StringBuffer msg = new StringBuffer();
			msg.append("您上载的文件中第");
			while (entries.hasNext()) {
				Map.Entry<String, Object> entry = (Entry<String, Object>) entries.next();
				System.out.println("Value = " + entry.getValue());
				msg.append(entry.getValue() + "；");
			}

			hhvo.setMes(msg.toString().substring(0, msg.length() - 1).concat("行人员信息一致，请修改并重新上载文件！"));
			hhalist.add(hhvo);
			hhamap.put("hhmapData", hhalist);
			return hhamap;
		}

		// 处理保存
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				String checkSql = checkExcelFile(list.get(i));
				if (StringUtils.hasText(checkSql)) {

					HhAlertMessage hhvo = new HhAlertMessage();
					String mags = "消息：上传失败，附件名：" + list.get(i).getfJFileName() + "，行号：" + list.get(i).getfJRowNum()
							+ "，备注：" + checkSql + "";
					hhvo.setMes(mags);
					hhalist.add(hhvo);
				}
			}
			// else {
			//
			// service.processIntegrityBeanList(list);
			// }
		}

		if (hhalist.size() != 0) {
			hhamap.put("hhmapData", hhalist);
			return hhamap;
		} else {
			service.processIntegrityBeanList(list);
		}

		hhamap.put("hhmapData", hhalist);
		HhAlertMessage hhvok = new HhAlertMessage();
		hhvok.setMes(TrustConstants.UPLOAD_SUCCESS);

		List<HhAlertMessage> hhalistok = new ArrayList<HhAlertMessage>();
		hhalistok.add(hhvok);
		hhamap.put("hhmapDataOk", hhalistok);

		return hhamap;
	}

	/**
	 * 校验上传的excel是否格式正确
	 * 
	 * @param list
	 * @return
	 */
	private String checkExcelFile(IntegrityBlackDTO bean) {
		StringBuffer sql = new StringBuffer();
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd");
		String name = bean.getName();
		String gender = bean.getGender();
		String cardType = bean.getCardType();
		String cardNo = bean.getCardNo();
		String personCard = bean.getPersonCard();
		String inBlackReason = bean.getInBlackReason();
		String happenDateStr = bean.getHappenDateStr();
		String startDateStr = bean.getStartDateStr();
		String endDateStr = bean.getEndDateStr();
		// String phoneNumber = bean.getPhoneNumber();
		// String mobileNumber = bean.getMobileNumber();
		String attentionLevel = bean.getAttentionLevel();
		String attentionTime = bean.getAttentionTime();
		String illegal = bean.getIllegal();

		if (!StringUtils.hasText(name)) {
			sql.append("姓名不能为空！");
		}

		if (!StringUtils.hasText(gender)) {
			sql.append("性别不能为空！");
		}
		if (!StringUtils.hasText(personCard)) {
			sql.append("保险号不能为空！");
		} else {
			IntegrityBlackDTO currentBean = this.service.getIntegrityBlackDTOBySociationNum(personCard);
			if (currentBean == null) {
				sql.append("保险号[" + personCard + "]不存在！");
			}
		}
		if (!StringUtils.hasText(cardType)) {
			sql.append("证件类型不能为空！");
		}
		if (!StringUtils.hasText(cardNo)) {
			sql.append("证件号不能为空！");
		}

		// cth if (!StringUtils.hasText(phoneNumber)) {
		// sql.append("电话号码不能为空！");
		// break;
		// }
		// if (!StringUtils.hasText(mobileNumber)) {
		// sql.append("手机号码不能为空！");
		// break;
		// }
		// if (happenDate == null) {
		// sql.append("案发时间不能为空！");
		// break;
		// }
		if (!StringUtils.hasText(happenDateStr)) {
			sql.append("案发时间不能为空！");
		} else {
			try {
				bean.setHappenDate(sd.parse(happenDateStr));
			} catch (ParseException e) {
				sql.append("案发时间输入数据不正确（格式yyyymmdd）！");
			}
		}

		if (!StringUtils.hasText(attentionLevel)) {// 关注级别
			sql.append("关注级别不能为空！");
		}else{
			attentionLevel = attentionLevel.split("\\\\")[0];
			attentionLevel = attentionLevel.replace("级别", "");
			
			bean.setAttentionLevel(attentionLevel);
		}
		// cth if (!StringUtils.hasText(attentionTime)) {// 关注时限
		// sql.append("关注时限不能为空！");
		// break;
		// }
		if (!StringUtils.hasText(illegal)) {// 违规情节
			sql.append("违规情节不能为空！");
		} else {
			List<IntegrityBlackDTO> crtList = this.service.queryattentionMidIdCilckList(attentionLevel);
			if (crtList == null || crtList.size() == 0) {
				sql.append("所填的关注级别不存在！");
			} else {
				boolean err = true;
				for (IntegrityBlackDTO currentBean : crtList) {
//					if (!currentBean.getAttentionTime().equals(ggsxInt.toString())) {
//						sql.append("关注时限选择错误！");
//						break;
//					}
					if (currentBean.getIllegal().equals(illegal)) {
						err = !err;
						break;
					}
				}
				if (err) {
					sql.append("违规情节选择错误！");
				}
			}
		}

		Integer ggsxInt = 0;
 
		if (attentionLevel.equals("A")) {
			ggsxInt = 0;
		} else if (attentionLevel.equals("B")) {
			ggsxInt = 5;
		} else if (attentionLevel.equals("C")) {
			ggsxInt = 3;
		} else if (attentionLevel.equals("D")) {
			ggsxInt = 2;
		} else if (attentionLevel.equals("E")) {
			ggsxInt = 1;
		}
	 
		if (startDateStr == null) {
			sql.append("有效开始时间不能为空！");
		} else {
			try {
				bean.setStartDate(sd.parse(startDateStr));
			} catch (ParseException e) {
				sql.append("有效开始时间输入数据不正确（格式yyyymmdd）！");
			}
		}
		if (endDateStr == null) {
			sql.append("有效结束时间不能为空！");
		} else {
			try {
				Date endDate = sd.parse(endDateStr);
				bean.setEndDate(endDate);
				String startDate2 = sd2.format(bean.getStartDate());
				String strYY = startDate2.split("-")[0];
				Integer yyyy = Integer.parseInt(strYY) + ggsxInt;
				String startDate3 = yyyy.toString() + "-" + startDate2.split("-")[1] + "-" + startDate2.split("-")[2];

				String startDate4 = sd2.format(endDate);
				if (null != startDate4) {
					/*
					if (startDate4.equals("9999-01-01") && attentionLevel.equals("A")) {

					} else {
						if (!startDate3.equals(startDate4)) {
							sql.append("有效结束时间填写错误！（终身：9999-01-01）");
						}
					}*/
					if(attentionLevel.equals("A")){
						if(!startDate4.equals("9999-01-01"))
						{
							sql.append("有效结束时间填写错误！（终身：9999-01-01）");
						}
					}else{
						if (!startDate3.equals(startDate4)) {
							sql.append("有效结束时间填写错误,应为开始时间与对应关注时限的和。");
						}
					}
				}
			} catch (ParseException e) {
				sql.append("有效结束时间输入数据不正确（格式yyyymmdd）！");
			}
		}
		if (!StringUtils.hasText(inBlackReason)) {
			sql.append("备注（原进入黑名单原因）！");
		}

		 if(service.querySameParamPerson(name, cardNo, cardType)>0){
			 sql.append("该人员信息系统已经存在!");
		 }

		return sql.toString();

	}

	private IntegrityBlackDTO getIntegrityBlackDTOFromRow(HSSFRow row, String opertionUser) {

		if (row != null) {
			IntegrityBlackDTO bean = new IntegrityBlackDTO();
			int cellNum = row.getLastCellNum(); // 每行有多少列(格)
			for (int k = 0; k < cellNum; k++) // 此循环用来规范数据,如果某个格子里没有数据为空,
												// // 则替换成--
			{
				String value = "";
				if (row.getCell(k) != null) {
					value = row.getCell(k).toString().trim();
				} else {
					continue;
				}

				if (!StringUtils.hasText(value)) {
					continue;
				}

				if (k == 0) { // name
					bean.setName(value);
				} else if (k == 1) { // gender
					if (value.equals("男")) {
						bean.setGender("M");
					} else if (value.equals("女")) {
						bean.setGender("F");
					}
				} else if (k == 2) { // 保险号
					bean.setPersonCard(value);
				} else if (k == 3) { // 证件类型
					if (value.equals("身份证")) {
						bean.setCardType("1");
					} else if (value.equals("军官证")) {
						bean.setCardType("3");
					} else if (value.equals("护照")) {
						bean.setCardType("2");
					} else if (value.equals("少儿证")) {
						bean.setCardType("4");
					} else if (value.equals("台胞证")) {
						bean.setCardType("5");
					} else if (value.equals("港澳台通行证")) {
						bean.setCardType("6");
					} else if (value.equals("其他")) {
						bean.setCardType("9");
					} else if (value.equals("转换不详")) {
						bean.setCardType("8");
					}
				} else if (k == 4) { // 证件号
					bean.setCardNo(value);
				} else if (k == 5) {// 电话号码
					bean.setPhoneNumber(value);
				} else if (k == 6) {// 手机号码
					bean.setMobileNumber(value);
				} else if (k == 7) { // 案发时间
					// Date date = ConstantsUtils.getStringFormateDate(value);
					bean.setHappenDateStr(value);
				} else if (k == 8) {// 关注级别
					bean.setAttentionLevel(value);
				} 
//				else if (k == 9) {// 关注时限
//					bean.setAttentionTime(value);
//				} 
				else if (k == 9) {// 关注级别
					bean.setIllegal(value);
				} else if (k == 10) { // 有效时间开始
					// Date startDate =
					// ConstantsUtils.getStringFormateDate(value);
					bean.setStartDateStr(value);
				} else if (k == 11) {// 有效结束时间
					// Date endDate =
					// ConstantsUtils.getStringFormateDate(value);
					bean.setEndDateStr(value);
				} else if (k == 12) { // 备注（原进入黑名单原因）
					bean.setInBlackReason(value);
				}

			}

			bean.setCreateDate(new Date());
			bean.setOpertionUser(opertionUser);
			bean.setUpdateDate(new Date());
			bean.setStatus(TrustConstants.status_01);
			return bean;
		} else {
			return null;
		}

	}

	/**
	 * 查询参保人信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("queryIntegrityBlackData.do")
	@ResponseBody
	public IntegrityResponseBean queryIntegrityBlackData(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {

		BlackParamterCondtion condition = new BlackParamterCondtion();
		String name = vo.getName();

		String processState = vo.getProcessState();

		String currentName = ConstantsUtils.processSqlName(name);

		String personCard = vo.getPersonCard();
		int page = vo.getPage();
		int pageSize = vo.getPageSize();

		int start = (page - 1) * pageSize;
		int end = start + pageSize;

		condition.setStart(start);
		condition.setEnd(end);
		condition.setName(currentName);
		if (StringUtils.hasText(personCard)) {
			condition.setPersonCard("%" + personCard + "%");
		}
		if (StringUtils.hasText(processState)) {
			condition.setProcessState(processState);
		}
		condition.setHappenDateStart(vo.getStartDate());
		condition.setHappenDateEnd(vo.getEndDate());
		condition.setCreateStartDate(vo.getCreateStartDate());
		condition.setCrateEndDate(vo.getCrateEndDate());
		condition.setSwiftCode(vo.getSwiftCode());
		
		IntegrityResponseBean bean = new IntegrityResponseBean();

		List<IntegrityBlackDTO> list = this.service.queryIntegrityBlackDTO(condition);

		long count = this.service.queryIntegrityBlackDTOCount(condition);
		bean.setResult(list);
		bean.setTotal(count);
		return bean;
	}

	/**
	 * 获取登陆系统的用户信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("initDataUser.do")
	@ResponseBody
	public IntegrityResponseBean initDataUser(@ModelAttribute InterityBlackAddRequestVO vo, HttpServletRequest request) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");

		IntegrityResponseBean returnBean = new IntegrityResponseBean();
		returnBean.setMessage(user.getUsername());
		return returnBean;
	}

	@RequestMapping("updateIntegrityBlack.do")
	@ResponseBody
	public IntegrityResponseBean updateIntegrityBlack(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");

		IntegrityBlackDTO bean = new IntegrityBlackDTO();
		bean.setName(vo.getName());
		bean.setGender(vo.getGender());
		bean.setCardNo(vo.getCardNo());
		bean.setCardType(vo.getCardType());

		bean.setInBlackReason(vo.getInBlackReason());
		bean.setPersonCard(vo.getPersonCard());
		bean.setStatus(TrustConstants.status_01);
		bean.setUpdateDate(new Date());
		bean.setOpertionUser(user.getUsername());

		String startStr = vo.getStartDate();
		String endStr = vo.getEndDate();
		String happenDateStr = vo.getHappenDate();

		Date startDate = ConstantsUtils.getStringFormateDate(startStr);
		Date endDate = ConstantsUtils.getStringFormateDate(endStr);

		Date happenDate = ConstantsUtils.getStringFormateDate(happenDateStr);

		bean.setStartDate(startDate);
		bean.setEndDate(endDate);
		bean.setHappenDate(happenDate);
		bean.setId(vo.getId());
		bean.setPhoneNumber(vo.getPhoneNumber());
		bean.setMobileNumber(vo.getMobileNumber());
		bean.setProcessState(TrustConstants.process_state_01);
		bean.setAttentionMidId(vo.getAttentionMidId());
		IntegrityResponseBean returnBean = new IntegrityResponseBean();
		try {
			this.service.updateIntegrityBlackDTO(bean);
			returnBean.setStatus(true);
			returnBean.setMessage("更新成功了");
		} catch (Exception es) {
			returnBean.setStatus(false);
			returnBean.setMessage("更新失败了");
			es.printStackTrace();
		}

		return returnBean;
	}

	/**
	 * 增加参保黑名单信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("addIntegrityBlack.do")
	@ResponseBody
	public IntegrityResponseBean addIntegrityBlack(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");
		String regionCode = this.kpiRegionCodeService.getRegionCode(user.getUserId());
		IntegrityBlackDTO bean = new IntegrityBlackDTO();
		bean.setName(vo.getName());
		bean.setCreateDate(new Date());
		bean.setGender(vo.getGender());
		bean.setCardNo(vo.getCardNo());
		bean.setCardType(vo.getCardType());
		bean.setAlPhabetic(vo.getPingy());

		bean.setInBlackReason(vo.getInBlackReason());
		bean.setPersonCard(vo.getPersonCard());
		bean.setStatus(TrustConstants.status_01);
		bean.setUpdateDate(new Date());
		bean.setOpertionUser(user.getUsername());

		String startStr = vo.getStartDate();
		String endStr = vo.getEndDate();
		String happenDateStr = vo.getHappenDate();

		Date startDate = ConstantsUtils.getStringFormateDate(startStr);
		Date endDate = ConstantsUtils.getStringFormateDate(endStr);

		Date happenDate = ConstantsUtils.getStringFormateDate(happenDateStr);

		bean.setStartDate(startDate);
		bean.setEndDate(endDate);
		bean.setHappenDate(happenDate);
		bean.setRegionCode(regionCode);
		bean.setProcessState(TrustConstants.process_state_01);
		bean.setPhoneNumber(vo.getPhoneNumber());
		bean.setMobileNumber(vo.getMobileNumber());
		bean.setAttentionMidId(vo.getAttentionMidId());
		try {
			List<Map<String, Object>> resultList = service.getCurrentSwiftNumber();
			Map<String, Object> resultMap = resultList.get(0);
			int i = Integer.parseInt((String) resultMap.get("num"));
			String dateStr = (String) resultMap.get("dateStr");
			SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
			//SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
			Map<String,Object> paraMap=new HashMap<String,Object>();
			if(dateStr.equals(sdf.format(new Date())))
			{
				i=i+1;
				paraMap.put("num",new Integer(i).toString());
			}
			else{
				paraMap.put("num","1");
				paraMap.put("dateStr", sdf.format(new Date()));
			}
			service.updateCurrentSwiftNumber(paraMap);
			List<Map<String, Object>> rList = service.getCurrentSwiftNumber();
			Map<String, Object> rMap = rList.get(0);
			int swiftNum = Integer.parseInt((String) rMap.get("num"));
			SimpleDateFormat sdf3 = new SimpleDateFormat("yyMMdd");
			String swiftNumber=sdf3.format(new Date()).concat(new Integer(swiftNum).toString());
			bean.setSwiftNumber(swiftNumber);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		IntegrityResponseBean returnBean = new IntegrityResponseBean();
		try {
			this.service.saveIntegrityBean(bean);
			returnBean.setStatus(true);
			returnBean.setMessage("保存成功了");
		} catch (Exception es) {
			returnBean.setStatus(false);
			returnBean.setMessage("保存失败了");
			es.printStackTrace();
		}

		return returnBean;
	}

	@RequestMapping("initAttentionLevelList.do")
	@ResponseBody
	public List<Map<String, Object>> initAttentionLevelList(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {

		List<Map<String, Object>> list = null;

		String attentionLevelId = vo.getAttentionLevelId();
		if (StringUtils.hasText(attentionLevelId)) {
			list = this.service.queryAttentionLevelInfo(TrustConstants.type_01, attentionLevelId);

		} else {
			list = this.service.queryAttentionLevelInfo(TrustConstants.type_02, "");
		}

		return list;

	}

	/**
	 * 撤销操作
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("cancelBuinsessProcess.do")
	@ResponseBody
	public Map<String, Object> cancelBuinsessProcess(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String blackId = vo.getId();
			if (StringUtils.hasText(blackId)) {
				map = this.service.cancelBuinsessProcess(blackId);
			}

		} catch (Exception es) {
			map.put("flag", false);
			map.put("msg", es.getCause().getMessage());
			log.error(es.getMessage());

		}

		return map;

	}

	@RequestMapping("resetBlackExcel.do")
	@ResponseBody
	public Map<String, Object> resetBlackExcel(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();

		System.out.println(request.getSession().getServletContext() + "\n\n");

		// String reportTemplatePath = reportTemplatePath +
		// "template/blackTemplate.xls";
		// String filePath =
		// request.getSession().getServletContext().getRealPath("views\\hcpms\\file");
		String fileNameResource = "template/resource_blackTemplate.xls";
		String fileNameTarget = "template/blackTemplate.xls";
		System.out.println(reportTemplatePath);
		log.info(reportTemplatePath);
		System.out.println("\n\n\n\n\n");
		FileInputStream fis = null;
		BufferedOutputStream bos = null;
		try {
			service.queryBlackWithExportExcel(reportTemplatePath, fileNameResource, fileNameTarget);

			log.info("current path==" + reportTemplatePath + fileNameTarget);

			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment; filename=\"" + new String("blackTemplate.xls".getBytes("GBK"), "iso8859-1") + "\"");

			fis = new FileInputStream(reportTemplatePath + fileNameTarget);
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[2048];
			while (fis.read(buffer) != -1) {
				bos.write(buffer);
				bos.flush();
			}

		} catch (BusinessException e) {
			e.printStackTrace();
			map.put("flag", false);
			// map.put("msg", e.getCause().getMessage());
			log.error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			// map.put("msg", e.getCause().getMessage());
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return map;

	}
	
}
